package com.logistic.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jxl.Workbook;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logistic.common.Excel;
import com.logistic.common.Files;
import com.logistic.domain.Record;
import com.logistic.domain.User;
import com.logistic.service.RecordService;
import com.logistic.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

public class RecordAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private RecordService recordService;

	private List list;
	private int limit;
	private int start;
	private int total;

	private File upload;

	// 上传文件的文件名
	private String uploadFileName;

	/**
	 * 
	 */
	public String list() {

		if (String.valueOf(start) == null)
			start = 0;
		if (String.valueOf(limit) == null)
			limit = 100;

		// 排序字段
		HttpServletRequest request = ServletActionContext.getRequest();
		String sort = (String) request.getAttribute("sort");
		if (sort == null || sort.equals("")) {
			sort = "id";
		}

		list = recordService.findRecordAll(sort);
		if (list == null) {
			total = 0;
		} else {
			total = list.size();
		}

		StringBuffer jsonStr = new StringBuffer("[");

		if (start + limit > total)
			limit = total - start;

		// 统计部分
		double tzze_num = 0; // 投资总额
		double lywz_num = 0; // 利用外资
		double yztd_num = 0; // 预征土地
		double zczj_num = 0; // 注册资金
		double zdmj_num = 0; // 占地面积
		double tdjg_num = 0; // 土地价格

		for (int i = start; i < start + limit; i++) {

			Record record = (Record) list.get(i);

			jsonStr.append("{");

			jsonStr.append("id:'").append(i + 1).append("',");
			
			jsonStr.append("xh:'").append(record.getId()).append("',");

//			if (record.getXh() == null || record.getXh().equals("null")) {
//				jsonStr.append("xh:'").append("").append("',");
//			} else {
//				jsonStr.append("xh:'").append(record.getXh()).append("',");
//			}

			if (record.getXmbh() == null || record.getXmbh().equals("null")) {
				jsonStr.append("xmbh:'").append("").append("',");
			} else {
				jsonStr.append("xmbh:'").append(record.getXmbh()).append("',");
			}

			if (record.getXmmc() == null || record.getXmmc().equals("null")) {
				jsonStr.append("xmmc:'").append("").append("',");
			} else {
				jsonStr.append("xmmc:'").append(record.getXmmc()).append("',");
			}

			if (record.getTzf() == null || record.getTzf().equals("null")) {
				jsonStr.append("tzf:'").append("").append("',");
			} else {
				jsonStr.append("tzf:'").append(record.getTzf().trim())
						.append("',");
			}

			if (record.getCpcl() == null || record.getCpcl().equals("null")) {
				jsonStr.append("cpcl:'").append("").append("',");
			} else {
				jsonStr.append("cpcl:'").append(record.getCpcl()).append("',");
			}

			if (record.getTzze() == null || record.getTzze().equals("null")) {
				jsonStr.append("tzze:'").append("").append("',");
			} else {
				jsonStr.append("tzze:'").append(record.getTzze()).append("',");
			}

			if (record.getTzze() != null && !record.getTzze().equals("null")
					&& !record.getTzze().equals("")) {
				tzze_num = tzze_num + Double.parseDouble(record.getTzze());
			}

			if (record.getYztd() == null || record.getYztd().equals("null")) {
				jsonStr.append("yztd:'").append("").append("',");
			} else {
				jsonStr.append("yztd:'").append(record.getYztd()).append("',");
			}

			if (record.getYztd() != null && !record.getYztd().equals("null")
					&& !record.getYztd().equals("")) {
				yztd_num = yztd_num + Double.parseDouble(record.getYztd());
			}

			if (record.getZczj() == null || record.getZczj().equals("null")) {
				jsonStr.append("zczj:'").append("").append("',");
			} else {
				jsonStr.append("zczj:'").append(record.getZczj()).append("',");
			}

			if (record.getZczj() != null && !record.getZczj().equals("null")
					&& !record.getZczj().equals("")) {
				zczj_num = zczj_num + Double.parseDouble(record.getZczj());
			}

			if (record.getLywz() == null || record.getLywz().equals("null")) {
				jsonStr.append("lywz:'").append("").append("',");
			} else {
				jsonStr.append("lywz:'").append(record.getLywz()).append("',");
			}

			if (record.getLywz() != null && !record.getLywz().equals("null")
					&& !record.getLywz().equals("")) {
				lywz_num = lywz_num + Double.parseDouble(record.getLywz());
			}

			if (record.getGxjsqy() == null || record.getGxjsqy().equals("null")) {
				jsonStr.append("gxjsqy:'").append("").append("',");
			} else {
				jsonStr.append("gxjsqy:'").append(record.getGxjsqy())
						.append("',");
			}

			if (record.getXmlyd() == null || record.getXmlyd().equals("null")) {
				jsonStr.append("xmlyd:'").append("").append("',");
			} else {
				jsonStr.append("xmlyd:'").append(record.getXmlyd())
						.append("',");
			}

			if (record.getQylxr() == null || record.getQylxr().equals("null")) {
				jsonStr.append("qylxr:'").append("").append("',");
			} else {
				jsonStr.append("qylxr:'").append(record.getQylxr())
						.append("',");
			}

			if (record.getQylxr_lxdh() == null
					|| record.getQylxr_lxdh().equals("null")) {
				jsonStr.append("qylxr_lxdh:'").append("").append("',");
			} else {
				jsonStr.append("qylxr_lxdh:'").append(record.getQylxr_lxdh())
						.append("',");
			}

			if (record.getXmjsr() == null || record.getXmjsr().equals("null")) {
				jsonStr.append("xmjsr:'").append("").append("',");
			} else {
				jsonStr.append("xmjsr:'").append(record.getXmjsr())
						.append("',");
			}

			if (record.getXmjsr_lxdh() == null
					|| record.getXmjsr_lxdh().equals("null")) {
				jsonStr.append("xmjsr_lxdh:'").append("").append("',");
			} else {
				jsonStr.append("xmjsr_lxdh:'").append(record.getXmjsr_lxdh())
						.append("',");
			}

			if (record.getFgjz() == null || record.getFgjz().equals("null")) {
				jsonStr.append("fgjz:'").append("").append("',");
			} else {
				jsonStr.append("fgjz:'").append(record.getFgjz()).append("',");
			}

			if (record.getYyzz() == null || record.getYyzz().equals("null")) {
				jsonStr.append("yyzz:'").append("").append("',");
			} else {
				jsonStr.append("yyzz:'").append(record.getYyzz()).append("',");
			}

			if (record.getSwdjz() == null || record.getSwdjz().equals("null")) {
				jsonStr.append("swdjz:'").append("").append("',");
			} else {
				jsonStr.append("swdjz:'").append(record.getSwdjz())
						.append("',");
			}

			if (record.getZzjgdmz() == null
					|| record.getZzjgdmz().equals("null")) {
				jsonStr.append("zzjgdmz:'").append("").append("',");
			} else {
				jsonStr.append("zzjgdmz:'").append(record.getZzjgdmz())
						.append("',");
			}

			if (record.getXmkxxbgs() == null
					|| record.getXmkxxbgs().equals("null")) {
				jsonStr.append("xmkxxbgs:'").append("").append("',");
			} else {
				jsonStr.append("xmkxxbgs:'").append(record.getXmkxxbgs())
						.append("',");
			}

			if (record.getQtxgzl() == null || record.getQtxgzl().equals("null")) {
				jsonStr.append("qtxgzl:'").append("").append("',");
			} else {
				jsonStr.append("qtxgzl:'").append(record.getQtxgzl())
						.append("',");
			}

			if (record.getXybh() == null || record.getXybh().equals("null")) {
				jsonStr.append("xybh:'").append("").append("',");
			} else {
				jsonStr.append("xybh:'").append(record.getXybh()).append("',");
			}

			if (record.getZdmj() == null || record.getZdmj().equals("null")) {
				jsonStr.append("zdmj:'").append("").append("',");
			} else {
				jsonStr.append("zdmj:'").append(record.getZdmj()).append("',");
			}

			if (record.getZdmj() != null && !record.getZdmj().equals("null")
					&& !record.getZdmj().equals("")) {
				zdmj_num = zdmj_num + Double.parseDouble(record.getZdmj());
			}

			if (record.getTdwz() == null || record.getTdwz().equals("null")) {
				jsonStr.append("tdwz:'").append("").append("',");
			} else {
				jsonStr.append("tdwz:'").append(record.getTdwz()).append("',");
			}

			if (record.getTdjg() == null || record.getTdjg().equals("null")) {
				jsonStr.append("tdjg:'").append("").append("',");
			} else {
				jsonStr.append("tdjg:'").append(record.getTdjg()).append("',");
			}

			if (record.getTdjg() != null && !record.getTdjg().equals("null")
					&& !record.getTdjg().equals("")) {
				tdjg_num = tdjg_num + Double.parseDouble(record.getTdjg());
			}

			if (record.getQyrq() == null || record.getQyrq().equals("null")) {
				jsonStr.append("qyrq:'").append("").append("'");
			} else {
				jsonStr.append("qyrq:'").append(record.getQyrq()).append("'");
			}

			if (i == start + limit - 1) {
				jsonStr.append("}, {xh:'',xmmc:'合计：',tzf:'',cpcl:'',tzze:'"
						+ tzze_num
						+ "',yztd:'"
						+ yztd_num
						+ "',zczj:'"
						+ zczj_num
						+ "',lywz:'"
						+ lywz_num
						+ "',gxjsqy:'',xmlyd:'',qylxr:'',qylxr_lxdh:'',xmjsr:'',xmjsr_lxdh:'',fgjz:'',yyzz:'',swdjz:'',zzjgdmz:'',xmkxxbgs:'',qtxgzl:'',xybh:'',zdmj:'"
						+ zdmj_num + "',tdwz:'',tdjg:'" + tdjg_num
						+ "',qyrq:''}");
				// jsonStr.append("}");
			} else {
				jsonStr.append("},");
			}
		}

		jsonStr.append("]");

		String str = "{totalProperty: " + total + ", root:"
				+ jsonStr.toString() + "}";

		// str="{totalProperty: 1, root:[{xh:'',xmmc:'疏堵结合',tzf:'士大夫',cpcl:'第三方',tzze:'null',yztd:'null',zczj:'null',lywz:'null',gxjsqy:'null',xmlyd:'null'}]}";
		// System.out.println("str:" + str);

		request.setAttribute("result", str);

		return "success";
	}

	/**
	 * 保存
	 */
	public String save() {

		HttpServletRequest request = ServletActionContext.getRequest();
		String xhStr = (String) request.getAttribute("xhStr");

		Record record = new Record();

		record.setXmbh(this.getXmbh());
		record.setXmmc(this.getXmmc());
		record.setTzf(this.getTzf());
		record.setTzze(this.getTzze());
		record.setCpcl(this.getCpcl());
		record.setYztd(this.getYztd());
		record.setZczj(this.getZczj());
		record.setLywz(this.getLywz());
		record.setGxjsqy(this.getGxjsqy());
		record.setXmlyd(this.getXmlyd());
		record.setFgjz(this.getFgjz());
		record.setQylxr(this.getQylxr());
		record.setQylxr_lxdh(this.getQylxr_lxdh());
		record.setXmjsr(this.getXmjsr());
		record.setXmjsr_lxdh(this.getXmjsr_lxdh());

		record.setYyzz(this.getYyzz());
		record.setSwdjz(this.getSwdjz());
		record.setZzjgdmz(this.getZzjgdmz());
		record.setXmkxxbgs(this.getXmkxxbgs());
		record.setQtxgzl(this.getQtxgzl());

		record.setXybh(this.getXybh());
		record.setZdmj(this.getZdmj());
		record.setTdjg(this.getTdjg());
		record.setTdwz(this.getTdwz());
		record.setQyrq(this.getQyrq());

		record.setSfsc("1"); // 未删除

		if (xhStr.equals("-1")) { // 新增
			recordService.save(record);
		//	request.setAttribute("result", "{success:true,message:'ok'}");
		} else { // 修改
			record.setId(xhStr);
			recordService.modify(record);
		}

		request.setAttribute("result", "{success:true,message:'ok'}");

		return "success";
	}

	/**
	 * 删除
	 */
	public String delete() {

		HttpServletRequest request = ServletActionContext.getRequest();
		String xhStr = (String) request.getAttribute("xhStr");
		recordService.deleteByIdStr(xhStr);

		return "success";
	}

	/**
	 * 生成excel
	 */
	@SuppressWarnings("rawtypes")
	public String printExcel() {

		// 创建当前日子
		Date date = new Date();
		// 格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		// 格式化日期(产生文件名)
		String filename = sdf.format(date);

		// 创建文件
		File f = new File("D://" + filename + ".xls");
		try {
			f.createNewFile();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();

		String headNameStr = request.getParameter("headNameStr"); // 拆分字符串得到表头信息

		String title[] = null;
		if (!"".equals(headNameStr) && null != headNameStr) {
			String str1 = headNameStr.substring(0, headNameStr.length() - 1);
			title = str1.split(",");
		}

		String xhStr = request.getParameter("xhStr"); // 每一行的数据
		String data1[] = null;
		if (!"".equals(xhStr) && null != xhStr) {
			String dataStr1 = xhStr.substring(0, xhStr.length() - 1);
			data1 = dataStr1.split("&");
		}

		List<List> lists = new ArrayList<List>();

		List<String> list3 = new ArrayList<String>();
		list3.add("a");
		list3.add("b");
		list3.add("c");
		for (int i = 0; i < data1.length; i++) {

			String data2[] = null;
			if (!"".equals(data1[i]) && null != data1[i]) {
				String dataStr2 = data1[i].substring(0, data1[i].length() - 1);
				data2 = dataStr2.split(",");
			}

			List<String> list1 = new ArrayList<String>();
			if (data2 != null) {
				for (int j = 0; j < data2.length; j++) {
					list1.add(data2[j]);
				}
			}

			lists.add(list1);
		}

		Excel excels = new Excel();

		// 生成excel文件(保存在服务器机上)
		try {
			excels.writeExcel(new FileOutputStream(f), title, lists);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 导出文件(下载到客户机上,并删除服务器机上的excel文件)
		Files files = new Files();
		try {
			files.exportFile(response, request, f, true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 上传Excel
	 * 
	 * @return
	 * @throws IOException
	 */
	public String uploadExcel() throws IOException {
		HttpServletRequest request = ServletActionContext.getRequest();

		// 首先判断用户是否曾经上传过,如果上传过,则删掉原来的文件(这里我没考虑其他情况,考虑周全还要写一些代码)
		String oldFileName = request.getParameter("upload");
		// 如果存在则删除
		if (!"noFile".equalsIgnoreCase(oldFileName)) {
			File oldFile = new File(ServletActionContext.getServletContext()
					.getRealPath("/") + "uploadFiles/" + oldFileName);
			oldFile.delete();
		}

		// 为用户上传的文件新取一个名字
		Calendar day = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String newName = sdf.format(day.getTime());
		// 获取用户上传的文件格式
		String exp = getFileExp(this.getUploadFileName());

		// 将文件写入文件夹
		FileOutputStream fos = new FileOutputStream(ServletActionContext
				.getServletContext().getRealPath("/")
				+ "uploadFiles/"
				+ newName + exp);

		FileInputStream fis = new FileInputStream(upload);
		byte[] buffer = new byte[10240];
		int len = 0;

		// int total = fis.available(); // 大小
		while ((len = fis.read(buffer)) > 0) {
			fos.write(buffer, 0, len);
			fos.flush();
		}
		fis.close();
		fos.close();
		// 返回图片名称(路径我是在前台写死了的),注意返回的contentType不能是text/json;
		request.setAttribute("result", "{success:true,message:'OK'}");

		HttpServletResponse response = ServletActionContext.getResponse();
		Excel excels = new Excel();
		String newFileName = ServletActionContext
		.getServletContext().getRealPath("/")
		+ "uploadFiles/"
		+ newName + exp;
		excels.readExcel(newFileName, response.getWriter());
		
		return SUCCESS;

	}

	// 获取文件格式(扩展名)
	private String getFileExp(String name) {
		int pos = name.lastIndexOf(".");
		return name.substring(pos);
	}

	

	public RecordService getRecordService() {
		return recordService;
	}

	public void setRecordService(RecordService recordService) {
		this.recordService = recordService;
	}

	@SuppressWarnings("rawtypes")
	public List getList() {
		return list;
	}

	@SuppressWarnings("rawtypes")
	public void setList(List list) {
		this.list = list;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	private String xh;
	private String xmbh;
	private String xmmc;
	private String tzf;
	private String cpcl;
	private String tzze;
	private String yztd;
	private String zczj;
	private String lywz;
	private String gxjsqy;
	private String xmlyd;

	private String qylxr;
	private String qylxr_lxdh;
	private String xmjsr;
	private String xmjsr_lxdh;
	private String fgjz;
	private String yyzz;
	private String swdjz;
	private String zzjgdmz;
	private String xmkxxbgs;

	private String qtxgzl;
	private String xybh;
	private String zdmj;
	private String tdwz;
	private String tdjg;
	private String qyrq;

	private String xhStr;

	public String getXh() {
		return xh;
	}

	public void setXh(String xh) {
		this.xh = xh;
	}

	public String getXmbh() {
		return xmbh;
	}

	public void setXmbh(String xmbh) {
		this.xmbh = xmbh;
	}

	public String getXmmc() {
		return xmmc;
	}

	public void setXmmc(String xmmc) {
		this.xmmc = xmmc;
	}

	public String getTzf() {
		return tzf;
	}

	public void setTzf(String tzf) {
		this.tzf = tzf;
	}

	public String getCpcl() {
		return cpcl;
	}

	public void setCpcl(String cpcl) {
		this.cpcl = cpcl;
	}

	public String getTzze() {
		return tzze;
	}

	public void setTzze(String tzze) {
		this.tzze = tzze;
	}

	public String getYztd() {
		return yztd;
	}

	public void setYztd(String yztd) {
		this.yztd = yztd;
	}

	public String getZczj() {
		return zczj;
	}

	public void setZczj(String zczj) {
		this.zczj = zczj;
	}

	public String getLywz() {
		return lywz;
	}

	public void setLywz(String lywz) {
		this.lywz = lywz;
	}

	public String getGxjsqy() {
		return gxjsqy;
	}

	public void setGxjsqy(String gxjsqy) {
		this.gxjsqy = gxjsqy;
	}

	public String getXmlyd() {
		return xmlyd;
	}

	public void setXmlyd(String xmlyd) {
		this.xmlyd = xmlyd;
	}

	public String getQylxr() {
		return qylxr;
	}

	public void setQylxr(String qylxr) {
		this.qylxr = qylxr;
	}

	public String getQylxr_lxdh() {
		return qylxr_lxdh;
	}

	public void setQylxr_lxdh(String qylxr_lxdh) {
		this.qylxr_lxdh = qylxr_lxdh;
	}

	public String getXmjsr() {
		return xmjsr;
	}

	public void setXmjsr(String xmjsr) {
		this.xmjsr = xmjsr;
	}

	public String getXmjsr_lxdh() {
		return xmjsr_lxdh;
	}

	public void setXmjsr_lxdh(String xmjsr_lxdh) {
		this.xmjsr_lxdh = xmjsr_lxdh;
	}

	public String getFgjz() {
		return fgjz;
	}

	public void setFgjz(String fgjz) {
		this.fgjz = fgjz;
	}

	public String getYyzz() {
		return yyzz;
	}

	public void setYyzz(String yyzz) {
		this.yyzz = yyzz;
	}

	public String getSwdjz() {
		return swdjz;
	}

	public void setSwdjz(String swdjz) {
		this.swdjz = swdjz;
	}

	public String getZzjgdmz() {
		return zzjgdmz;
	}

	public void setZzjgdmz(String zzjgdmz) {
		this.zzjgdmz = zzjgdmz;
	}

	public String getXmkxxbgs() {
		return xmkxxbgs;
	}

	public void setXmkxxbgs(String xmkxxbgs) {
		this.xmkxxbgs = xmkxxbgs;
	}

	public String getQtxgzl() {
		return qtxgzl;
	}

	public void setQtxgzl(String qtxgzl) {
		this.qtxgzl = qtxgzl;
	}

	public String getXybh() {
		return xybh;
	}

	public void setXybh(String xybh) {
		this.xybh = xybh;
	}

	public String getZdmj() {
		return zdmj;
	}

	public void setZdmj(String zdmj) {
		this.zdmj = zdmj;
	}

	public String getTdwz() {
		return tdwz;
	}

	public void setTdwz(String tdwz) {
		this.tdwz = tdwz;
	}

	public String getTdjg() {
		return tdjg;
	}

	public void setTdjg(String tdjg) {
		this.tdjg = tdjg;
	}

	public String getQyrq() {
		return qyrq;
	}

	public void setQyrq(String qyrq) {
		this.qyrq = qyrq;
	}

	public void setXhStr(String xhStr) {
		this.xhStr = xhStr;
	}

	public String getXhStr() {
		return xhStr;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}
}
